from app.api_v1_0 import api
from flask import session, request, jsonify, current_app, redirect, url_for
from app import models, constants, redis, db
from app.utils.response_code import RET  # 导入自定义的响应码
from app.utils.commons import login_required


@api.route('/test')
def test():
    session['username'] = "Augus"

    return "test html"


@api.route('/users/auth', methods=["POST", "GET"])
@login_required
def auth_add():

    # 用于对当前用户账户进行实名验证页面：两条路：当该账号已经实名化，则前端应该为GET请求，走GET分支处理；当该账号未被实名化，则前端为POST请求，走POST分支处理

    try:
        user_id = session.get("user_id")
        # print(f'***************', user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if request.method == "POST":
        req_dict = request.get_json()
        id_card = req_dict.get('id_card')
        real_name = req_dict.get('real_name')

        # print(f'id_card:{id_card}, real_name:{real_name}')

        try:
            user = db.session.query(models.User).get(user_id)
            user.real_name = real_name
            user.id_card = id_card

            db.session.commit()

        except Exception as e:
            db.session.rollback()
            db.session.flush()

            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")

        return jsonify(errno=RET.OK)

    else:
        try:
            user = db.session.query(models.User).get(user_id)
            real_name = user.real_name
            id_card = user.id_card

            # print("***", user)
            # print("*********", real_name, "******", id_card)


        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")

        return jsonify(errno=RET.OK, data={"real_name": real_name, "id_card": id_card})



@api.route('users/name', methods=["PUT"])
@login_required
def modify_username():

    username = request.get_json().get('name')
    print(f'username:{username}')

    try:
        user_id = session.get("user_id")
        # print(f'***************', user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    try:
        user = db.session.query(models.User).get(user_id)

        user.name = username

        db.session.commit()

        # 因为在修改 `api.route("user"), 发现有bug, 故添此句话
        session["name"] = username

    except Exception as e:
        db.session.rollback()
        db.session.flush()

        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    return jsonify(errno=RET.OK, errmsg="modify successfully")


@api.route('user')
@login_required
def getUser():
    user_name = session.get('name')
    mobile = session.get('mobile')

    user_id = session.get('user_id')

    try:

        user = db.session.query(models.User).get(user_id)
        avatar = user.avatar_url
    except Exception as e:

        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not all([user_name, mobile]):
        return jsonify(errno="4101")

    return jsonify(errno=RET.OK, data={"name": user_name, "mobile": mobile, "avatar": constants.QINIU_DOMIN_PREFIX + str(avatar)})


